package com.mediacloud.app.newsmodule.fragment

import android.text.TextUtils
import android.util.Log
import android.widget.AbsListView
import com.eventTrack.TXReportManager.Companion.getInstance
import com.jeremyliao.liveeventbus.LiveEventBus
import com.mediacloud.app.model.ZiMeiTiAttentionListNull
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.ShowSwitch
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.basenews.IAdapterRefresh
import com.mediacloud.app.newsmodule.fragment.baoliao.api.FacadeApi
import com.mediacloud.app.newsmodule.fragment.newslist.IntelligentRecommendFragment
import com.mediacloud.app.newsmodule.fragment.newslist.TXRecommendFragment
import com.mediacloud.app.reslib.enums.GlobalSwitch
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.util.*

var searchId: String? = null//用来存放搜索点击的id

fun BaseNewsListFragmentX.preload(preNum: Int, access_token: String? = null) {
    var params: MutableMap<String, String>? = null
    if (!TextUtils.isEmpty(access_token)) {
        params = HashMap()
        params["access_token"] = "$access_token"
    }
    if (searchId != null) {
        if (params == null)
            params = HashMap()
        params["only_article"] = "1"
        params["catid_cover"] = searchId!!
    }
    if (nid != 0) {
        if (params != null) {
            params["catid_cover"] = nid.toString()
        } else {
            params = HashMap()
            params["catid_cover"] = nid.toString()
        }
    }
    val d = DataInvokeUtil.getContentList(catalogID, preNum, pageSize, params)
        .map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn {
            null
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<ArticleListData> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(t: ArticleListData) {
                preLoadKit?.hasMore = t.more
                preLoadKit?.onPreloadSuccess(t, preNum)
            }

            override fun onError(e: Throwable) {
                preLoadKit?.onPreloadFail(preNum)

            }

            override fun onComplete() {

            }
        })

}

fun BaseNewsListFragmentX.getData(access_token: String? = null) {
    var params: MutableMap<String, String>? = null
    if (!TextUtils.isEmpty(access_token)) {
        params = HashMap()
        params["access_token"] = "$access_token"
    }
    if (searchId != null) {
        if (params == null)
            params = HashMap()
        params["only_article"] = "1"
        params["catid_cover"] = searchId!!
    }
    if (nid != 0) {
        if (params != null) {
            params["catid_cover"] = nid.toString()
        } else {
            params = HashMap()
            params["catid_cover"] = nid.toString()
        }
    }

    DataInvokeUtil.getContentList(catalogID, preLoadKit!!.pageNum, pageSize, params)
        .map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn {
            null
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<ArticleListData> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(t: ArticleListData) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                preLoadKit?.hasMore = t.more
                preLoadKit?.preLoadData?.add(t)
                setData(t)
                preLoadKit.preload()
            }

            override fun onError(e: Throwable) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }

                mXSmartRefreshLayout.finishRefresh(false)
                mXSmartRefreshLayout.finishLoadMore()
                if (adaptor.listContentData != null && adaptor.listContentData.size > 0) {
                    closeStateView()
                } else {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                }
            }

            override fun onComplete() {

            }
        })


}


fun BaseNewsListFragmentX.preloadAttention(preNum: Int, access_token: String? = null) {
    var params: MutableMap<String, String>? = null
    if (!TextUtils.isEmpty(access_token)) {
        params = HashMap()
        params["access_token"] = "$access_token"
    }
    if (searchId != null) {
        if (params == null)
            params = HashMap()
        params["only_article"] = "1"
        params["catid_cover"] = searchId!!
    }

    val d = DataInvokeUtil.getAttentionList(preNum, pageSize, params)
        .map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn {
            null
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<ArticleListData> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(t: ArticleListData) {
                preLoadKit?.hasMore = t.more
                preLoadKit?.onPreloadSuccess(t, preNum)
            }

            override fun onError(e: Throwable) {
                preLoadKit?.onPreloadFail(preNum)

            }

            override fun onComplete() {

            }
        })

}

fun BaseNewsListFragmentX.getData(access_token: String? = null, index: Int? = null, count: Int? = null) {
    var params: MutableMap<String, String>? = null
    if (!TextUtils.isEmpty(access_token)) {
        params = HashMap()
        params["access_token"] = "$access_token"
    }
    if (searchId != null) {
        if (params == null)
            params = HashMap()
        params["only_article"] = "1"
        params["catid_cover"] = searchId!!
    }
    if (nid != 0) {
        if (params != null) {
            params["catid_cover"] = nid.toString()
        } else {
            params = HashMap()
            params["catid_cover"] = nid.toString()
        }
    }
//    if (params != null){
//        params["index"] = index!!.toString()
//        params["count"] = count!!.toString()
//    }else{
//        params = HashMap()
//        params["index"] = index!!.toString()
//        params["count"] = count!!.toString()
//    }

    DataInvokeUtil.getContentList(catalogID, preLoadKit!!.pageNum, pageSize, params)
        .map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn {
            null
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<ArticleListData> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(t: ArticleListData) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                setData(t)
            }

            override fun onError(e: Throwable) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }

                mXSmartRefreshLayout.finishRefresh(false)
                mXSmartRefreshLayout.finishLoadMore()
                if (adaptor.listContentData != null && adaptor.listContentData.size > 0) {
                    closeStateView();
                } else {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                }
            }

            override fun onComplete() {

            }
        })


}

fun BaseNewsListFragmentX.preload(preNum: Int, access_token: String? = null,  count: Int? = null) {
    var params: MutableMap<String, String>? = null
    if (!TextUtils.isEmpty(access_token)) {
        params = HashMap()
        params["access_token"] = "$access_token"
    }
    if (searchId != null) {
        if (params == null)
            params = HashMap()
        params["only_article"] = "1"
        params["catid_cover"] = searchId!!
    }
    if (nid != 0) {
        if (params != null) {
            params["catid_cover"] = nid.toString()
        } else {
            params = HashMap()
            params["catid_cover"] = nid.toString()
        }
    }
    if (params != null){
        params["index"] = preNum.toString()
        params["count"] = count!!.toString()
    }else{
        params = HashMap()
        params["index"] = preNum.toString()
        params["count"] = count!!.toString()
    }
    val d = DataInvokeUtil.getContentList(catalogID, preNum, pageSize, params)
        .map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn {
            null
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<ArticleListData> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(t: ArticleListData) {
                preLoadKit?.hasMore = t.more
                preLoadKit?.onPreloadSuccess(t, preNum)
            }

            override fun onError(e: Throwable) {
                preLoadKit?.onPreloadFail(preNum)

            }

            override fun onComplete() {

            }
        })

}


fun TXRecommendFragment.getRefreshData(access_token: String? = null) {
    //智能推荐置顶请求
    FacadeApi.getSpiderCmsApiJson(activity)
        .getIntelligentTop(getString(R.string.tenantid))
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<JSONObject> {
            override fun onSubscribe(d: Disposable) {}
            override fun onNext(jsonObject: JSONObject) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                articleListTop.clear()
                val state = jsonObject.optBoolean("state")
                if (state) {
                    val topMeta = jsonObject.optJSONArray("data")
                    if (topMeta != null && topMeta.length() > 0) {
                        for (i in 0 until topMeta.length()) {
                            val jsonObject1 = topMeta.optJSONObject(i)
                            if (jsonObject1 != null) {
                                try {
                                    val item = ArticleItem.parse(jsonObject1)
                                    val showSwitch = ShowSwitch()
                                    showSwitch.allowShowHitCount = true
                                    showSwitch.allowShowInteractionCount = false
                                    showSwitch.allowShowPublishDate = true
                                    showSwitch.allowShowSource = true
                                    showSwitch.allowShowComment = true
                                    item.setmShowSwitch(showSwitch)
                                    if (item.cmsCustomStyle == null) {
                                        item.appCustomParams = item.appCustomParams
                                    }
                                    item.isFromTop = true
                                    articleListTop.add(item)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    }
                }
                if (articleListTop != null && articleListTop.size > 0) {
                    for (i in 0 until articleListTop.size) {
                        if (articleListTop.get(i) != null) {
                            getInstance().app_jhapp_rec_content_exp(
                                null,
                                null,
                                articleListTop.get(i).getId().toString() + "",
                                getInstance().getContentShowType(articleListTop.get(i).getType())
                            )
                        }
                    }
                }
                recommendRvAdapter.setNewData(articleListTop)
                getIntelligentRecommend(preLoadKit!!.pageNum)
            }

            override fun onError(e: Throwable) {
                getIntelligentRecommend(preLoadKit!!.pageNum)
            }

            override fun onComplete() {}
        })
}

fun TXRecommendFragment.getRandomNumber(): Int {
    if (preLoadKit!!.pageNum > 1) {
        return 20
    }
    val random = Random()
    val i = random.nextInt(30 - 15 + 1) + 15 // 生成 15-30 之间的随机整数
    return i
}

fun TXRecommendFragment.preloadIntelligentRecommend(preNum: Int) {
    //智能推荐推荐请求
    val dataRecommend: Observable<JSONObject> = if (userInfo.isLogin) {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            userInfo.userid,
            preNum,
            getRandomNumber(),
            false
        )
    } else {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            preNum,
            getRandomNumber(),
            false
        )
    }
    dataRecommend.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<JSONObject> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(jsonObject: JSONObject) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                val state = jsonObject.optBoolean("state")
                if (state) {
                    val topMeta = jsonObject.optJSONArray("data")
                    if (topMeta != null && topMeta.length() > 0) {
                        val data = ArticleListData()
                        data.articleList = ArrayList<ArticleItem>()
                        for (i in 0 until topMeta.length()) {
                            val jsonObject1 = topMeta.optJSONObject(i)
                            if (jsonObject1 != null) {
                                try {
                                    val item = ArticleItem.parse(jsonObject1)
                                    val showSwitch = ShowSwitch()
                                    showSwitch.allowShowHitCount = true
                                    showSwitch.allowShowInteractionCount = false
                                    showSwitch.allowShowPublishDate = true
                                    showSwitch.allowShowSource = true
                                    showSwitch.allowShowComment = true
                                    item.setmShowSwitch(showSwitch)
                                    if (item.cmsCustomStyle == null) {
                                        item.appCustomParams = item.appCustomParams
                                    }
                                    item.isFromTop = false
                                    data.articleList.add(item)
                                    //articleListBody.add(item)
                                    // mArticleListData.articleList.add(item)
                                } catch (e: java.lang.Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }

                        preLoadKit?.onPreloadSuccess(data, preNum)

                    } else {
                        preLoadKit?.onPreloadFail(preNum)
                    }
                    preLoadKit?.hasMore = topMeta != null && topMeta.length() != 0
                } else {
                    preLoadKit?.onPreloadFail(preNum)
                }
            }

            override fun onError(e: Throwable) {
                preLoadKit?.onPreloadFail(preNum)
            }

            override fun onComplete() {}
        })
}

fun TXRecommendFragment.getIntelligentRecommend(preNum: Int) {
    //智能推荐推荐请求
    val dataRecommend: Observable<JSONObject> = if (userInfo.isLogin) {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            userInfo.userid,
            preNum,
            getRandomNumber(),
            false
        )
    } else {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            preNum,
            getRandomNumber(),
            false
        )
    }
    dataRecommend.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<JSONObject> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(jsonObject: JSONObject) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                mXSmartRefreshLayout.finishRefresh()
                if (preNum == 1) {
                    // articleListBody.clear()
                    //  mArticleListData.articleList.clear()
//                        mArticleListData.articleList.addAll(articleListTop)
                    if (adaptor is IAdapterRefresh) {
                        (adaptor as IAdapterRefresh).refresh()
                    }
                }
                val state = jsonObject.optBoolean("state")
                if (state) {
                    val topMeta = jsonObject.optJSONArray("data")
                    var data = ArticleListData()
                    data.articleList = java.util.ArrayList()
                    if (topMeta != null && topMeta.length() > 0) {

                        data.articleList = ArrayList<ArticleItem>()
                        for (i in 0 until topMeta.length()) {
                            val jsonObject1 = topMeta.optJSONObject(i)
                            if (jsonObject1 != null) {
                                try {
                                    val item = ArticleItem.parse(jsonObject1)
                                    val showSwitch = ShowSwitch()
                                    showSwitch.allowShowHitCount = true
                                    showSwitch.allowShowInteractionCount = false
                                    showSwitch.allowShowPublishDate = true
                                    showSwitch.allowShowSource = true
                                    showSwitch.allowShowComment = true
                                    item.setmShowSwitch(showSwitch)
                                    if (item.cmsCustomStyle == null) {
                                        item.appCustomParams = item.appCustomParams
                                    }
                                    item.isFromTop = false
                                    //articleListBody.add(item)
                                    data.articleList.add(item)
                                } catch (e: java.lang.Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }


                    } else {
                        preLoadKit?.onPreloadFail(preNum)
                    }
                    try {
                        val topMeta = jsonObject.optJSONArray("data")
                        setData(data)
                        preLoadKit?.hasMore = topMeta?.length() != 0
                        preLoadKit?.preLoadData?.add(data)
                        preLoadKit.preload()
                    } catch (e: Exception) {
                    }
                } else {
                    preLoadKit?.onPreloadFail(preNum)
                }

                if (preNum == 1) {
                    mXSmartRefreshLayout.finishRefresh()
                    mXSmartRefreshLayout.finishLoadMore()
                    curPosition = -1
                    visiblePosition = 0
                    firstPosition = 0
                    //触发一下 onScrollStateChanged 否则 视频不会自动播放
                    mCatalogContentItemListView.postDelayed({
                        if (onScrollListener != null) {
                            onScrollListener.onScrollStateChanged(
                                mCatalogContentItemListView,
                                AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                            )
                        }
                    }, 300)
                }
                LiveEventBus.get(XKey.FINISH_MODE).post(true)
                if (adaptor.listContentData.size <= 0) {
                    showStateView(TYPE_NO_CONTENT, false)
                } else {
                    closeStateView()
                }
                Log.w("6666666", "list======: " + adaptor.listContentData.size)

            }

            override fun onError(e: Throwable) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }

                isLoading = false
                preLoadKit!!.pageNum--
                mXSmartRefreshLayout.finishRefresh(false)
                mXSmartRefreshLayout.finishLoadMore()
                if (e != null && adaptor != null && (adaptor.listContentData == null
                            || adaptor.listContentData.size == 0)
                ) {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                } else if (adaptor != null && (adaptor.listContentData == null
                            || adaptor.listContentData.size == 0)
                ) {
                    showStateView(TYPE_NO_CONTENT, false)
                } else closeStateView()
                preLoadKit?.onPreloadFail(preNum)
            }

            override fun onComplete() {}
        })
}

fun BaseNewsListFragmentX.getDataX(access_token: String? = null) {
    var params: MutableMap<String, String>? = null
    if (!TextUtils.isEmpty(access_token)) {
        params = HashMap()
        params["access_token"] = "$access_token"
    }
    if (searchId != null) {
        if (params == null)
            params = HashMap()
        params["only_article"] = "1"
        params["catid_cover"] = searchId!!
    }
    if (nid != 0) {
        if (params != null) {
            params["catid_cover"] = nid.toString()
        } else {
            params = HashMap()
            params["catid_cover"] = nid.toString()
        }
    }

    DataInvokeUtil.getContentList(catalogID, preLoadKit!!.pageNum, pageSize, params)
        .map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn {
            null
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<ArticleListData> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(t: ArticleListData) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                getAttentionData(access_token, t.componentItems)
            }

            override fun onError(e: Throwable) {
                getAttentionData(access_token, null)
            }

            override fun onComplete() {

            }
        })


}


fun BaseNewsListFragmentX.getAttentionData(
    access_token: String? = null,
    componentItems: ArrayList<ComponentItem?>?
) {
    var params: MutableMap<String, String?>? = null
    if (!TextUtils.isEmpty(access_token)) {
        params = HashMap()
        params["access_token"] = "$access_token"
    }
    if (searchId != null) {
        if (params == null)
            params = HashMap()
        params["only_article"] = "1"
        params["catid_cover"] = searchId!!
    }
    val d = DataInvokeUtil.getAttentionList(preLoadKit!!.pageNum, pageSize, params)
        .map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp.articleList.forEach {
                //这里强制赋值一下。找不到原因。解析的时候时正确的，解析完成又变成别的值了。偶现
                it.mShowSwitch?.apply {
                    allowShowHitCount = GlobalSwitch.allowShowHitCount
                    allowShowInteractionCount = GlobalSwitch.allowShowInteractionCount
                    allowShowPublishDate = GlobalSwitch.allowShowPublishDate
                    allowShowSource = GlobalSwitch.allowShowSource
                    allowShowComment = GlobalSwitch.allowShowComment
                }
            }
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn {
            null
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<ArticleListData> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(t: ArticleListData) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }

                if (t.articleList != null && t.articleList.size > 0) {
                    EventBus.getDefault().post(ZiMeiTiAttentionListNull(false))
                    preLoadKit?.hasMore = t.more
                    preLoadKit?.preLoadData?.add(t)
                    if (componentItems != null && componentItems.size > 0) {
                        t.componentItems.clear()
                        t.componentItems.addAll(componentItems)
                    }
                    setData(t)
                    preLoadKit.preload()
                } else {
                    val articleListData = ArticleListData()
                    if (componentItems != null && componentItems.size > 0) {
                        articleListData.componentItems.addAll(componentItems)
                    }
                    setData(articleListData)
                    EventBus.getDefault().post(ZiMeiTiAttentionListNull(true))
                }

            }

            override fun onError(e: Throwable) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }

                mXSmartRefreshLayout.finishRefresh(false)
                mXSmartRefreshLayout.finishLoadMore()
                if (adaptor.listContentData != null && adaptor.listContentData.size > 0) {
                    closeStateView();
                } else {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                }
            }

            override fun onComplete() {

            }
        })
}

fun BaseNewsListFragmentX.releaseData() {
    if (disposables.isNotEmpty()) {
        for (i in 0 until disposables.size) {
            if (!disposables[i].isDisposed) {
                disposables[i].dispose()
            }
        }
        disposables.clear()
    }
}



fun IntelligentRecommendFragment.preloadIntelligentRecommend(preNum: Int) {
    //智能推荐推荐请求
    val dataRecommend: Observable<JSONObject> = if (userInfo.isLogin) {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            userInfo.userid,
            preNum,
            20,
            false
        )
    } else {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            preNum,
            20,
            false
        )
    }
    dataRecommend.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<JSONObject> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(jsonObject: JSONObject) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                val state = jsonObject.optBoolean("state")
                if (state) {
                    val topMeta = jsonObject.optJSONArray("data")
                    if (topMeta != null && topMeta.length() > 0) {
                        val data = ArticleListData()
                        data.articleList = ArrayList<ArticleItem>()
                        for (i in 0 until topMeta.length()) {
                            val jsonObject1 = topMeta.optJSONObject(i)
                            if (jsonObject1 != null) {
//                                try {
                                    val item = ArticleItem.parse(jsonObject1)
                                    val showSwitch = ShowSwitch()
                                    showSwitch.allowShowHitCount = true
                                    showSwitch.allowShowInteractionCount = false
                                    showSwitch.allowShowPublishDate = true
                                    showSwitch.allowShowSource = true
                                    showSwitch.allowShowComment = true
                                    item.setmShowSwitch(showSwitch)
                                    if (item.cmsCustomStyle == null) {
                                        item.appCustomParams = item.appCustomParams
                                    }
                                    item.isFromTop = false
                                    data.articleList.add(item)
                                    //articleListBody.add(item)
                                    // mArticleListData.articleList.add(item)
//                                } catch (e: java.lang.Exception) {
//                                    e.printStackTrace()
//                                }
                            }
                        }
                        preLoadKit?.hasMore = true
                        preLoadKit?.onPreloadSuccess(data, preNum)

                    } else {
                        preLoadKit?.onPreloadFail(preNum)
                    }
                } else {
                    preLoadKit?.onPreloadFail(preNum)
                }
            }

            override fun onError(e: Throwable) {
                preLoadKit?.onPreloadFail(preNum)
            }

            override fun onComplete() {}
        })
}

fun IntelligentRecommendFragment.getIntelligentRecommend(preNum: Int) {
    //智能推荐推荐请求
    val dataRecommend: Observable<JSONObject> = if (userInfo.isLogin) {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            userInfo.userid,
            preNum,
            20,
            false
        )
    } else {
        FacadeApi.getSpiderCmsApiJson(activity).getIntelligentRecommend(
            if (TextUtils.isEmpty(uuidTx)) uuid else uuidTx,
            preNum,
            20,
            false
        )
    }
    dataRecommend.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<JSONObject> {
            override fun onSubscribe(d: Disposable) {
                disposables.add(d)
            }

            override fun onNext(jsonObject: JSONObject) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                mXSmartRefreshLayout.finishRefresh()
                if (preNum == 1) {
                    // articleListBody.clear()
                    //  mArticleListData.articleList.clear()
//                        mArticleListData.articleList.addAll(articleListTop)
                    if (adaptor is IAdapterRefresh) {
                        (adaptor as IAdapterRefresh).refresh()
                    }
                }
                val state = jsonObject.optBoolean("state")
                if (state) {
                    val topMeta = jsonObject.optJSONArray("data")
                    var data = ArticleListData()
                    data.articleList = java.util.ArrayList()
                    if (topMeta != null && topMeta.length() > 0) {

                        data.articleList = ArrayList<ArticleItem>()
                        for (i in 0 until topMeta.length()) {
                            val jsonObject1 = topMeta.optJSONObject(i)
                            if (jsonObject1 != null) {
//                                try {
                                    val item = ArticleItem.parse(jsonObject1)
                                    val showSwitch = ShowSwitch()
                                    showSwitch.allowShowHitCount = true
                                    showSwitch.allowShowInteractionCount = false
                                    showSwitch.allowShowPublishDate = true
                                    showSwitch.allowShowSource = true
                                    showSwitch.allowShowComment = true
                                    item.setmShowSwitch(showSwitch)
                                    if (item.cmsCustomStyle == null) {
                                        item.appCustomParams = item.appCustomParams
                                    }
                                    item.isFromTop = false
                                    //articleListBody.add(item)
                                    data.articleList.add(item)
//                                } catch (e: java.lang.Exception) {
//                                    e.printStackTrace()
//                                }
                            }
                        }


                    } else {
                        preLoadKit?.onPreloadFail(preNum)
                    }
                    try {
                        val topMeta = jsonObject.optJSONArray("data")
                        preLoadKit?.hasMore = topMeta?.length() != 0
                        preLoadKit?.preLoadData?.add(data)
                        setRecommendData(data)
                        preLoadKit.preload()
                    } catch (e: Exception) {
                    }
                } else {
                    setDe()
                    preLoadKit?.onPreloadFail(preNum)
                }

                if (adaptor.listContentData.size <= 0) {
                    setDe()
                    showStateView(TYPE_NO_CONTENT, false)
                } else {
                    closeStateView()
                }

            }

            override fun onError(e: Throwable) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                setDe()
                mXSmartRefreshLayout.finishRefresh(false)
                mXSmartRefreshLayout.finishLoadMore()
                if (adaptor.listContentData != null && adaptor.listContentData.size > 0) {
                    closeStateView();
                } else {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                }
            }

            override fun onComplete() {}
        })
}


